package com.security.control.core.social.wx.config;

import com.security.control.core.properties.SecurityProperties;
import com.security.control.core.properties.WxSocialProperties;
import com.security.control.core.social.view.MyConnectView;
import com.security.control.core.social.wx.connect.WxConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.social.config.annotation.ConnectionFactoryConfigurer;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.web.servlet.View;

/**
 * @author imoot@gamil.com
 * @date 2019/1/4 0004 16:01
 * -----在springboot2.x的版本开始移除了SocialAutoConfigurerAdapter，所以这里要继承SocialAutoConfigurerAdapter的父类SocialConfigurerAdapter
 */
@Configuration
@ConditionalOnProperty(prefix = "com.security.control.social.wx", name = "appId")//当yml中配置了appId时才启用
public class WxAutoConfig extends SocialConfigurerAdapter {

    @Autowired
    private SecurityProperties securityProperties;

    //添加连接工厂的数据库存储配置
    @Override
    public void addConnectionFactories(ConnectionFactoryConfigurer configurer, Environment environment) {
        configurer.addConnectionFactory(createConnectionFactory());
    }

    //用providerId、appId、appSecret构建wx授权登录连接工厂
    public ConnectionFactory<?> createConnectionFactory() {
        WxSocialProperties wxSocialProperties = securityProperties.getWxSocialProperties();
        return new WxConnectionFactory(wxSocialProperties.getProviderId(), wxSocialProperties.getAppId(), wxSocialProperties.getAppSecret());
    }

    //获取数据库存储类
    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        return super.getUsersConnectionRepository(connectionFactoryLocator);
    }

    @Bean(name = {"connect/wxcallbackConnected", "connect/wxcallbackConnect"})//解绑和绑定视图的区别在于：绑定会在服务商id后跟"Connected"，解绑会在服务商id后跟"Connect"
    @ConditionalOnMissingBean(name = "wxConnectedView")
    public View wxConnectedView() {
        return new MyConnectView();
    }

}
